package ckw.database.model;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PostLoad;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.Type;

import core.communication.configurationNode.AddConfigurationNode;
import core.communication.configurationNode.ConfigurationNode;
import core.communication.configurationNode.DeleteConfigurationNode;
import core.communication.configurationNode.EditConfigurationNode;
import core.communication.configurationNode.SetParentConfigurationNode;
import core.communication.message.Direction;
import core.database.AbstractEntity;
import core.utils.Converter;

@Entity
@Table(name = "nodeChanges")
public class NodeChanges extends AbstractEntity {

	@Column(name = "uri")
	private String uri;

	@Transient
	private List<ConfigurationNode> nodeActions = new ArrayList<ConfigurationNode>();

	@Column(name = "nodeActionsXML")
	@Type(type = "text")
	private String nodeActionsXML;

	public NodeChanges() {
	}

	public NodeChanges(String locatorUri) {
		this.uri = locatorUri;
	}

	public void onPersist() {
		convertListsToXml();
	}

	@PrePersist
	private void convertListsToXml() {
		nodeActionsXML = Converter.objectToXML(nodeActions);
	}

	@SuppressWarnings("unchecked")
	@PostConstruct
	@PostLoad
	private void converList() {
		nodeActions = (List<ConfigurationNode>) Converter.xmlToObject(nodeActionsXML);
	}

	public String getUri() {
		return uri;
	}

	public void setUri(String uri) {
		this.uri = uri;
	}

	public List<ConfigurationNode> getNodeActions() {
		return nodeActions;
	}

	public void setNodeActions(ArrayList<ConfigurationNode> nodeActions) {
		this.nodeActions = nodeActions;
	}

	public String getNodeActionsXML() {
		return nodeActionsXML;
	}

	public void setNodeActionsXML(String nodeActionsXML) {
		this.nodeActionsXML = nodeActionsXML;
	}

	public void addActionSetParent(String nodeUri) {
		nodeActions.add(new SetParentConfigurationNode(nodeUri));
	}

	public void addActionDelete(String nodeUri) {
		nodeActions.add(new DeleteConfigurationNode(nodeUri));
	}

	public void addActionAdd(Node node, Direction direction) {
		nodeActions.add(new AddConfigurationNode(node.toCNode(), direction));
	}

	public void addActionEdit(Node changedNode, String nodeUri, Direction direction) {
		nodeActions.add(new EditConfigurationNode(nodeUri, changedNode.toCNode(), direction));
	}
}
